<!--宠物信息-->
<template>
  <div class="row">
    <div class="container">
      <el-form :inline="true" class="demo-form-inline"
               :style="{marginTop: '20px',float: 'left'}">
        <el-form-item>
          <el-select style="width: 110px" filterable="" v-model="requestData.requestData.type" placeholder="请选择">
            <el-option
              v-for="item in initSelect.type"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-date-picker
            v-model="requestData.requestData.allTime"
            type="datetimerange"
            range-separator="至"
            value-format="yyyy-MM-dd HH:mm:ss"
            format="yyyy-MM-dd HH:mm:ss"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
          <el-button type="primary" @click="reset">重置</el-button>
          <el-button type="primary" @click="addVisible">新增</el-button>
        </el-form-item>
      </el-form>
      <el-table
        :data="list"
        stripe
        border
        size="mini"
        style="width: 100%;margin-top: 10px">
        <el-table-column
          type="index"
          label="序号"
          align="center"
          width="100">
        </el-table-column>

        <el-table-column
          prop="type"
          label="建议类型"
          align="center"
          :formatter="dataFormatter"
        >
        </el-table-column>

        <el-table-column
          prop="name"
          label="产品名称"
          align="center"
        >
        </el-table-column>

        <el-table-column
          prop="title"
          label="标题"
          align="center"
        >
        </el-table-column>

        <el-table-column
          prop="file_name"
          label="附件"
          align="center"
        >
          <template slot-scope="scope">
            <a :href="$a + '/tbowner/download?fileName=' + scope.row.file_name">{{ scope.row.file_name}}</a>
          </template>
        </el-table-column>

        <el-table-column
          prop="create_user"
          align="center"
          label="创建人">
        </el-table-column>
        <el-table-column
          prop="create_date"
          align="center"
          label="创建时间">
        </el-table-column>
        <el-table-column
          prop="update_date"
          align="center"
          label="修改时间">
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          align="center"
          width="250">
          <template slot-scope="scope">
            <el-button size="mini" @click="contentDts(scope.row)" type="warning">文章详细</el-button>
            <el-button size="mini" @click="editParam(scope.row)" type="warning">编辑</el-button>
            <el-button size="mini" type="danger" @click="deleteParam(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>


      <!--信息修改-->
      <el-dialog style="text-align: left;" width="80%" :title="addOrUpdate == 1 ? `宠物信息新增` : `宠物信息修改`" top="5vh"
                 :visible.sync="outerVisible">


        <el-form ref="form" :model="addParam" label-width="120px" style="margin-top: 30px">


          <el-form-item label="建议类型">
            <el-select filterable="" v-model="addParam.type" placeholder="建议类型">
              <el-option
                v-for="item in initSelect.type"
                :key="`user` + item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="产品名称">
            <el-input type="textarea" v-model="addParam.name"></el-input>
          </el-form-item>

          <el-form-item label="标题">
            <el-input type="textarea" v-model="addParam.title"></el-input>
          </el-form-item>


          <el-form-item label="建议内容">
            <quill-editor
              class="ql-editor"
              v-model="addParam.content"
              ref="myQuillEditor"
              :options="editorOption"
              @blur="onEditorBlur($event)"
              @focus="onEditorFocus($event)"
              @change="onEditorChange($event)"
              @click="onEditorChange($event)"
            >
            </quill-editor>
          </el-form-item>

          <el-form-item label="上传附件">
            <span v-if="addParam.file_name !== '' && addParam.file_name !== undefined">上传成功：{{addParam.file_name}}</span>
            <el-upload
              class="upload-demo"
              ref="businessLicense"
              action
              :data="{data:111}"
              :auto-upload="false"
              :on-change="CoverCodeUploadSectionFile"
              :file-list="fileList.cover_code"
              list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-form-item>


          <el-form-item label="是否公开">
            <!--<el-input type="textarea" v-model="addParam.matters_needing_attention"></el-input>-->
            <el-radio-group v-model="addParam.is_open">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>


        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="editSubmit">提交</el-button>
          <el-button type="info" @click="outerVisible = false">取消</el-button>
        </div>
      </el-dialog>

      <el-dialog style="text-align: left;" width="50%" title="视频上传" top="5vh"
                 :visible.sync="videoForm.show">
        <el-upload
          class="upload-demo"
          ref="businessLicense"
          action
          :data="{data:111}"
          :auto-upload="false"
          :on-change="VideoUploadSectionFile"
          :file-list="fileList.video_code"
          list-type="picture">
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传mp4文件</div>
        </el-upload>
      </el-dialog>


      <el-dialog style="text-align: left;" width="50%" title="建议内容详细" top="5vh"
                 :visible.sync="videoForm.content">

        <div class="ql-container ql-snow" style="border: 0px">
          <div class="ql-editor" v-html="contentHtml.content" />
        </div>

      </el-dialog>

    </div>
  </div>
</template>
<!--ql-video-->
<script>
  import Quill from "quill";
  import ImageResize from "quill-image-resize-module"; // 引用
  import {ImageDrop} from "quill-image-drop-module";
  import 'quill/dist/quill.snow.css'
  Quill.register("modules/imageDrop", ImageDrop);
  Quill.register("modules/imageResize", ImageResize); // 注册

  export default {
    name: "infoList",
    data() {
      let _self = this;
      return {
        videoForm: {
          show: false,
          content: false,
        },
        contentHtml: {},
        editorOption: {
          modules: {
            imageDrop: true, // 拖动加载图片组件。
            imageResize: { //调整大小组件。
              displayStyles: {
                backgroundColor: 'black',
                border: 'none',
                color: 'white'
              },
              modules: ['Resize', 'DisplaySize', 'Toolbar']
            },
            toolbar: {
              container: [
                ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线
                ['blockquote', 'code-block'], // 引用  代码块
                [{header: 1}, {header: 2}], // 1、2 级标题
                [{list: 'ordered'}, {list: 'bullet'}], // 有序、无序列表
                [{script: 'sub'}, {script: 'super'}], // 上标/下标
                [{indent: '-1'}, {indent: '+1'}], // 缩进
                [{direction: 'rtl'}], // 文本方向
                [{size: ['12px', false, '16px', '18px', '20px', '30px']}], // 字体大小
                [{header: [1, 2, 3, 4, 5, 6, false]}], // 标题
                [{color: []}, {background: []}], // 字体颜色、字体背景颜色
                [{font: [false, 'SimSun', 'SimHei', 'Microsoft-YaHei', 'KaiTi', 'FangSong', 'Arial']}], // 字体种类
                [{align: []}], // 对齐方式
                ['clean'], // 清除文本格式
                ['link', 'image', 'video']
              ],
              handlers: {
                'video': () => {
                  // 覆盖默认的上传视频，点击视频图标，显示弹窗
                  _self.videoForm.show = true
                }
              }
            },// 链接、图片、视频

          },
          placeholder: '请输入正文'
        },
        fileList: {
          pet_code: [],
        },
        list: [],
        fileList: {
          cover_code: [],
          video_code: []
        },
        total: 0,
        optionsUserId: [],
        outerVisible: false,
        approvalVisible: false,
        editAndDeleteButton: false,
        addOrUpdate: 1,//1增2改
        leaveDts: [],
        initSelect: {
          type: [
            {label: '产品功能建议', value: 1}, {label: '官方文档建议', value: 2}, {label: '售前服务建议', value: 3},
            {label: '售后服务建议', value: 4}, {label: '备案服务建议', value: 5}, {label: '其他建议', value: 6}
            ],
        },
        requestData: {
          current: 1,
          pageSize: 10,
          requestData: {
            type: '',
            allTime: '',
          }
        },
        addParam: {
          type:'',
          name:'',
          title:'',
          content:'',
          file_name:'',
          is_open:1,
        },
        labelName: {
          type: '建议类型未选择,请选择！',
          name: '产品名称未输入,请输入！',
          title: '标题为空,请输入！',
          content: '文章内容未输入,请输入！',
        },
      }
    },
    created() {
      this.initOptions()
      this.initButton()
      // this.user = JSON.parse(sessionStorage.getItem("userInfo"))
    },
    mounted() {
      this.initList()
    },
    methods: {
      downFile(row){

      },
      contentDts(row) {
        this.contentHtml = row
        this.videoForm.content = true
      },
      // 失去焦点事件
      onEditorBlur(quill) {
        console.log('editor blur!', quill)
      },
      // 获得焦点事件
      onEditorFocus(quill) {
        console.log('editor focus!', quill)
      },
      // 准备富文本编辑器
      onEditorReady(quill) {
        console.log('editor ready!', quill)
      },
      // 内容改变事件
      onEditorChange({quill, html, text}) {
        console.log('editor change!', quill, html, text)
        // this.addParam.content = html
      },


      /*文章封面*/
      CoverCodeUploadSectionFile(file) {

        this.fileList.cover_code = [];
        // const typeArr = ['image/png', 'image/gif', 'image/jpeg', 'image/jpg'];
       /* const typeArr = ['image/png', 'image/gif', 'image/jpeg', 'image/jpg', 'application/pdf', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/msword'];
        const isJPG = typeArr.indexOf(file.raw.type) !== -1;
        if (!isJPG) {
          this.$message.error('只能word,或者PDF!');
          this.$refs.upload.clearFiles();
          this.files = null;
          return;
        }*/
        this.files = file.raw;
        // FormData 对象
        let formData = new FormData();
        // 文件对象
        formData.append('file', this.files);
        let config = {
          headers: {
            'Content-Type': 'multipart/form-data'
          },
          methods: 'post'
        }
        this.service.post("/tbowner/fileUpload", formData, config).then(res => {
          this.addParam.file_name = res.data.filename
        })
      },
      /*视频上传*/
      VideoUploadSectionFile(file) {
        const typeArr = ['video/mp4'];
        const isJPG = typeArr.indexOf(file.raw.type) !== -1;
        if (!isJPG) {
          this.$message.error('只能mp4!');
          this.$refs.upload.clearFiles();
          this.files = null;
          return;
        }
        this.files = file.raw;
        // FormData 对象
        let formData = new FormData();
        // 文件对象
        formData.append('file', this.files);
        let config = {
          headers: {
            'Content-Type': 'multipart/form-data'
          },
          methods: 'post'
        }
        this.service.post("/tbowner/fileUpload", formData, config).then(res => {
          let fileName = this.$a + '/tbowner/video?fileName=' + res.data.filename
          this.videoForm.show = false
          const quill = this.$refs.myQuillEditor.quill;
          // 获取光标所在位置
          const length = quill.getSelection(true).index;
          // 插入图片  res.info为服务器返回的图片地址
          quill.insertEmbed(length, "video", fileName);
          // 调整光标到最后
          quill.setSelection(length + 1);
        })
      },


      initOptions() {
        this.service.get('/tbPetTypeInfo/getAll'
          , this.requestData)
          .then(result => {
            this.initSelect.pet_type = []
            let data = result.data.data;
            for (let i = 0; i < data.length; i++) {
              this.initSelect.pet_type.push({
                value: data[i].id,
                label: data[i].name
              })
            }
          })
      },
      checkParam() {
        for (let item in this.addParam) {
          if (this.addParam[item].length < 1) {
            return this.labelName[item];
          }
        }
        return null;
      },

      addVisible(status) {

        for (let item in this.addParam) {
          this.addParam[item] = ''
        }
        this.fileList.pet_code = []
        this.addParam.is_open = 1
        this.addOrUpdate = 1
        this.outerVisible = true
      },

      add() {
        if (this.checkParam() != null) {
          this.$message.error(this.checkParam());
          return false;
        }

        this.service.post('/tbRecommendation/add'
          , {data: this.addParam})
          .then(result => {
            let data = result.data;
            if (data.code == 500) {
              this.$message.error("请求失败：" + data.data)
            }
            if (data.data > 0) {
              this.$message.success('增加成功')
              for (let item in this.addParam) {
                this.addParam[item] = '';
              }
              for (let item in this.fileList) {
                this.fileList[item] = [];
              }
              this.initList();
              this.outerVisible = false
            } else {
              this.$message.error('增加失败')
            }
          })
      },

      /**公共变量*/
      dataFormatter(row, column) {
        let arrayData = this.initSelect[column.property];
        for (let i = 0; i < arrayData.length; i++) {
          if (arrayData[i].value == row[column.property]) {
            return arrayData[i].label
          }
        }
      },
      editSubmit() {
        if (this.addOrUpdate == 1) {
          this.add()
          return false
        }
        this.service.post('/tbRecommendation/add'
          , {data: this.addParam})
          .then(result => {
            let data = result.data;
            if (data.code == 500) {
              this.$message.error("请求失败：" + data.data)
            }
            if (data.data > 0) {
              this.$message.success('修改成功')
              this.initList();
              this.outerVisible = false;
            } else {
              this.$message.error('修改失败')
            }
          })
      },
      initList() {
        this.service.post('/tbRecommendation/list'
          , this.requestData)
          .then(result => {
            this.list = result.data.data.data;
          })
      },
      editParam(row) {
        this.addOrUpdate = 2
        this.addParam = JSON.parse(JSON.stringify(row));
        this.outerVisible = true;
      },
      deleteParam(row) {
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.service.post('/tbRecommendation/del'
            , {data: row.id})
            .then(result => {
              let data = result.data;
              if (data.data > 0) {
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                });
                this.initList()
              } else {
                this.$message({
                  type: 'info',
                  message: '已取消删除'
                });
              }
            });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      initButton() {
        let userInfo = sessionStorage.getItem("userInfo");
        if (userInfo == undefined || userInfo == null) {
          this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
            confirmButtonText: '确定',
            type: 'error'
          }).then(() => {
            this.$router.push('/home/login')
          })
          return false;
        }
        let json = JSON.parse(sessionStorage.getItem("userInfo"));
        if (json.role_id == 0) {
          this.editAndDeleteButton = true;
        }
      },
      onSubmit() {
        this.requestData.requestData.start_time = this.requestData.requestData.allTime[0]
        this.requestData.requestData.end_time = this.requestData.requestData.allTime[1]
        this.initList()
      },
      reset() {
        for (let item in this.requestData.requestData) {
          this.requestData.requestData[item] = '';
        }
      },
    }
  }
</script>

<style scoped>

</style>
